package cn.kgc.vue.shiro;

import cn.hutool.json.JSONUtil;
import cn.kgc.vue.commons.Const;
import cn.kgc.vue.commons.ResponseResult;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.io.PrintWriter;


/**
 * @Author 张航
 * @Date 2024/7/3
 * @Description 校验token的过滤器
 */

public class WebTokenFilter extends BasicHttpAuthenticationFilter {

    //请求是否被允许
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        PrintWriter writer=null;
        try {
            executeLogin(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json;charset=utf-8");
            try {
                writer=response.getWriter();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            ResponseResult message = ResponseResult.error().code(Const.UN_AUTH).message("token异常,请重新登录");
            String jsonStr= JSONUtil.toJsonStr(message);
            writer.write(jsonStr);
            return false;

        } finally {
            if(writer!=null){
                writer.close();
            }

        }
        return true;
        //return super.isAccessAllowed(request, response, mappedValue);
    }


    //执行登录方法
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求头中的token
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("authorization");
        String s1 = httpServletRequest.getHeader("s1");
        if (StringUtils.isBlank(token)) {
            throw new RuntimeException("请求的是受限资源,请认证后访问");
        }

        //获取认证主体
        Subject subject = getSubject(request, response);
        //登录方法  username password
        JWTToken jwtToken = new JWTToken(token,request,s1);

        subject.login(jwtToken);


        return true;
    }

    //在执行isAccessAllowed之前 先执行该方法，可以在该方法中设置跨域问题
    //用户在发起请求时，如果请求跨域 会先发生一个option请求来判定该接口是否允许跨域  状态码为200 则说明允许跨域

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        //设置响应头允许跨域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));

        //判断是不是option请求
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;

        }


        return super.preHandle(request, response);
    }


}
